import { empty, sleep } from "#Utils/helper.js";
import { Service } from "#Services/service.js"
import UserRepository from "#Repositorys/userRepository.js";
import jwt from '#Libs/auth/jwt.js';

class AuthService extends Service {

    /**
     *  登录
     * @param {any} params 
     */
    async login(params) {
        const { business, password, ...realParams } = params

        await UserRepository.newQuery(business)

        let userInfo = await UserRepository.findOne({ where: realParams })

        if (empty(userInfo)) {
            return this.error(404, '用户不存在')
        }

        let isOk = await UserRepository.validatePwd(password, userInfo.getDataValue('password'))

        if (!isOk) {
            return this.error(401, '密码错误')
        }

        if (await UserRepository.isDisable(userInfo)) {
            return this.error(401, '用户被禁用')
        }

        let token = jwt.sign({ id: userInfo.getDataValue('id') })

        return this.success({ token, userInfo: userInfo.dataValues })
    }

    /**
     *  注册
     * @param {any} params 
     */
    async register(params) {
        const { business, ...realParams } = params

        await UserRepository.newQuery(business)
        await UserRepository.create(realParams)

    }

}

export default new AuthService();